package org.geektime.task.sboauth.request;

import com.alibaba.fastjson.JSONObject;
import org.geektime.task.sboauth.config.OAuthConfig;
import org.geektime.task.sboauth.config.OAuthSourceEnum;
import org.geektime.task.sboauth.model.OAuthCallback;
import org.geektime.task.sboauth.model.OAuthToken;
import org.geektime.task.sboauth.model.OAuthUser;

/**
 * 2021年04月21日 22:33:19
 */
public class GiteeOAuthRequest extends AbstractOAuthRequest {


    public GiteeOAuthRequest(OAuthConfig config) {
        super(config, OAuthSourceEnum.GITEE);
    }

    @Override
    protected OAuthToken getAccessToken(OAuthCallback authCallback) {

        String response = doPostAuthorizationCode(authCallback.getCode());
        JSONObject accessTokenObject = JSONObject.parseObject(response);

        OAuthToken oAuthToken = new OAuthToken();
        oAuthToken.setAccessToken(accessTokenObject.getString("access_token"));
        oAuthToken.setExpireIn(accessTokenObject.getIntValue("expires_in"));
        oAuthToken.setRefreshToken(accessTokenObject.getString("refresh_token"));
        oAuthToken.setScope(accessTokenObject.getString("scope"));
//        accessTokenObject.getString("token_type")
        return oAuthToken;
    }

    @Override
    protected OAuthUser getUserInfo(OAuthToken authToken) {
        String userInfo = doGetUserInfo(authToken);
        JSONObject object = JSONObject.parseObject(userInfo);
//        this.checkResponse(object);
        OAuthUser oAuthUser = new OAuthUser();
        oAuthUser.setUsername(object.getString("login"));
        oAuthUser.setNickname(object.getString("name"));
        oAuthUser.setRawUserInfo(object);
        oAuthUser.setRemark(object.getString("bio"));

        oAuthUser.setUuid(object.getString("id"));
        return oAuthUser;
    }
}
